//
//  ProductPecSheetViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2022/8/4.
//

import UIKit

struct SelectSpecModel {
    var id: NSInteger?
    var name: String?
    var parameItem: ItemsModel?
}

typealias BlockHiddenActionView = () -> Void

class ProductPecSheetViewController: UIViewController {
    
    var hiddenActionViewBlock: BlockHiddenActionView!
    
    var bkgBtn: UIButton!
    var contentView: UIView! //装载tableView背景圆角时用
    var topView: UIView!
    var priceLab: UILabel!
    var goodsImageView: UIImageView!
    var tableView: BaseTableView!
    var detailModel: DetailModel!
    var moreSpecificationArray: [ParametersModel] = []//多规格
    var skuDTOListArray: [SkuDTOListModel] = []//sku
    var quantity = 1
    var bottomBkgView: UIView!
    var selectSku: SkuDTOListModel!
    var skuList: [SkuDTOListModel] = []
    var specList: [ParametersModel] = []
    var selectSpec: [SelectSpecModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.clear
        
        self.skuList = self.detailModel?.data?.skuDTOList ?? []
        self.selectSku = self.skuList[0]
        
        
        _ = self.skuList.map { sku in
            let skuParam = sku.parameterItems ?? []
            let temp = skuParam.compactMap({ spec in
                return "\(spec.id ?? 0)"
            })
            sku.paramIds = temp.sorted().joined(separator: ",")
        }
        
        ///创建选择对像
        self.specList = self.detailModel?.parameters ?? []
        _ = self.specList.map { aItem in
            var aObj = SelectSpecModel()
            aObj.name = aItem.name
            aObj.id = aItem.id
            aObj.parameItem = nil
            self.selectSpec.append(aObj)
        }
        
        //
        self.filterDefaultParam()
        _ = self.specList.map { paramItem in
            let aObj = paramItem.items ?? []
            _ = aObj.map { pItem in
                pItem.able = self.isTagEnAble(secName: paramItem.name ?? "", tag: pItem)
            }
        }
        
        self.initUI()
        self.initTableView()
        self.initConfirmBtn()
        self.moreSpecificationArray = self.detailModel?.parameters ?? []
    }
    
    func filterDefaultParam() {
        let allSpecArray = self.specList.compactMap { paramObj in
            return paramObj.items
        }.flatMap{$0}
        
        let tempSku = self.skuList[0]
        let tempSkuParamList = tempSku.parameterItems ?? []
        
        //设置选中状态
        _ = allSpecArray.map { itemObj in
            itemObj.select = false
        }
        
        
        //修改选中提selectSpec对像
        for skuParam in tempSkuParamList {
            for (aIndex, tempSelect) in self.selectSpec.enumerated() {
                if skuParam.parameterId ?? 0 == tempSelect.id ?? 0 {
                    let aItem = ItemsModel.init()
                    aItem.id = skuParam.id
                    aItem.name = skuParam.name
                    aItem.select = true
                    aItem.able = true
                    self.selectSpec[aIndex].parameItem = aItem
                    
                    _ = allSpecArray.map { child in
                        if child.id  == aItem.id {
                            child.select = true
                        }
                    }
                    break
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimationAction()
    }
    
    
    func initUI() {
        //背景蒙层
        self.view.backgroundColor = UIColor.clear
        bkgBtn = UIButton.init(type: UIButtonType.custom)
        bkgBtn.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0)
        bkgBtn.addTarget(self, action: #selector(hiddenActionView), for: .touchUpInside)
        self.view.addSubview(bkgBtn)
        
        self.contentView = UIView.init(frame: CGRect.init(x: 0, y: kScreenHeight, width: kScreenWidth, height: kScreenHeight))
        self.contentView.backgroundColor = UIColor.white
        self.bkgBtn.addSubview(self.contentView)
        
    }

    
    
    func initHeaderView(){
        
        self.topView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 160))
        self.topView.backgroundColor = .white
        self.contentView.addSubview(self.topView)
        
        let tempLab = UILabel.init(frame: .zero)
        tempLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        tempLab.textColor = UIColor.black
        tempLab.textAlignment = .center
        tempLab.backgroundColor = UIColor.clear
        tempLab.numberOfLines = 0
        tempLab.lineBreakMode = .byTruncatingTail
        tempLab.text = MMLocalizedString("select_specification", comment: "选择规格")
        self.contentView.addSubview(tempLab)
        
        self.goodsImageView = UIImageView(frame: CGRect(x: 14, y: 30, width: 90, height: 90))
        self.goodsImageView.layer.cornerRadius = 4
        self.goodsImageView.layer.masksToBounds = true
        self.topView.addSubview(self.goodsImageView)
        
        let imageArray = (self.detailModel?.data?.productImages ?? "").components(separatedBy: ",")
        if imageArray.count > 0{
            self.goodsImageView.sd_setImage(with: URL(string: imageArray[0]))
        }
  
        
        self.priceLab = UILabel.init(frame: CGRect(x: 10, y: 30, width: kScreenWidth - 36, height: 40))
        self.priceLab.textColor = Theme.mainColor
        self.priceLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 28)
        self.topView.addSubview(self.priceLab)
        self.priceLab.text = XTManageCenter.currentSign() + (self.dealPrice())
        
        
        tempLab.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(0)
            make.width.equalTo(300)
            make.height.equalTo(40)
        }
        self.goodsImageView.snp.makeConstraints { make in
            make.top.equalTo(40)
            make.left.equalTo(14)
            make.width.height.equalTo(90)
       
        }
        
        self.priceLab.snp.makeConstraints { make in
            make.left.equalTo(self.goodsImageView.snp.right).offset(14)
            make.centerY.equalTo(self.goodsImageView.snp.centerY)
        }
        
        
        let closeBtn = UIButton(frame: CGRect(x: kScreenWidth - 40, y: 3, width: 30, height: 30))
        closeBtn.setImage(UIImage(named: "icon_close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside)
        self.topView.addSubview(closeBtn)
       
    }
    
    
    
    func initTableView() {
        self.initHeaderView()
        self.tableView = BaseTableView(frame: CGRect(x: 0, y: 120, width: kScreenWidth, height: 1350), style: .grouped)
        self.tableView.backgroundColor = .white
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.register(SkuTableViewCell.self, forCellReuseIdentifier: "SkuTableViewCell")
        self.tableView.register(AddNumTableViewCell.self, forCellReuseIdentifier: "AddNumTableViewCell")
        self.tableView.estimatedRowHeight = 200
        self.tableView.separatorStyle = .none
        self.tableView.showsHorizontalScrollIndicator = false
        self.contentView.addSubview(self.tableView)
    }
    
    
    //确定
    func initConfirmBtn() {
        
        bottomBkgView = UIView(frame: CGRect(x: 0, y: self.tableView.frame.maxY, width: kScreenWidth, height: TabbarHeight))
        bottomBkgView.backgroundColor = .white
        self.contentView.addSubview(bottomBkgView)
        
        let addShoppingCarBtn = UIButton(frame: CGRect(x: 14, y: 0, width: kScreenWidth - 28, height: 46))
        addShoppingCarBtn.backgroundColor = Theme.mainColor
        addShoppingCarBtn.setTitle(MMLocalizedString("add_shoppingCar", comment: "加入购物车"), for: .normal)
        addShoppingCarBtn.setTitleColor(.white, for: .normal)
        addShoppingCarBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        addShoppingCarBtn.addTarget(self, action: #selector(addShoppingCarBtnAntion), for: .touchUpInside)
        addShoppingCarBtn.layer.cornerRadius = 8
        addShoppingCarBtn.layer.masksToBounds = true
        bottomBkgView.addSubview(addShoppingCarBtn)
        
    }
    
    //MARK: - Request
    
    ///修改购物数量车添加商品 addType 1：商品列表加入，2：购物车列表更改数量）
    func requestcartAddNum(skuId: Int,quantity: Int){
        
        if (self.selectSku.availableStock ?? 0) < quantity {
            self.view.makeToast(message: MMLocalizedString("inventory_shortage", comment: "库存不足"))
            return
        }
        self.view.showLoadingHUDText(nil)
        var param = NSMutableDictionary() as! [String: Any]
        
        param["skuId"] = "\(skuId)"
        param["quantity"] = "\(quantity)"
        param["addType"] = "1"
        if UserModule.shared.isLogined ?? false == false {  //未登录
            param["cartKey"] = XTManageCenter.getLocalStringDataValue(aKey: XTManageCenter.CartKey)
        }
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.cartDAddNum(param: param), objectType: AddShopingCartModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! AddShopingCartModel
            if resultObj.code == "1" {
                let model = resultObj.data
                self.view.makeToastBottom(message: MMLocalizedString("add_cart", comment: "加入购物车成功"))
                XTManageCenter.setLocalDataString(aKey: XTManageCenter.CartKey, aValue: model?.cartKey ?? "")
                self.cancelBtnAction()
            }else{
                self.view.makeToastBottom(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    //修改数量价格变化
    func alterNumPrice(){
        //价格
        
        var lowestPrice: Double {
            return min(self.detailModel?.data?.discountPrice ?? 0, self.detailModel?.data?.memberPrice ?? 0, self.detailModel?.data?.price ?? 0)
        }
        var tag: String {
            if lowestPrice == self.detailModel?.data?.memberPrice {
                return "vip"
            } else if lowestPrice == self.detailModel?.data?.discountPrice {
                return "特价"
            } else {
                return ""
            }
        }
        var totalMoney = 0.00
        var selectSkuprice = 0.0
        switch tag {
        case "vip":
            selectSkuprice = self.selectSku?.memberPrice ?? 0
        case "特价":
            selectSkuprice = self.selectSku?.discountPrice ?? 0
        default:
            selectSkuprice = self.selectSku?.price ?? 0
        }
        totalMoney = Double(quantity) * (selectSkuprice)//价格计算
        let totalPrice = XTManageCenter.showPriceInComma(source: (totalMoney).cleanZero)
        self.priceLab.text = XTManageCenter.currentSign() + totalPrice
    }
    
    //价格对比展示最低价
    func dealPrice() -> String{
        var lowestPrice: Double {
            return min(self.detailModel?.data?.discountPrice ?? 0, self.detailModel?.data?.memberPrice ?? 0, self.detailModel?.data?.price ?? 0)
          }
        
        var tag: String {
            if lowestPrice == self.detailModel?.data?.memberPrice {
                return "vip"
            } else if lowestPrice == self.detailModel?.data?.discountPrice {
                return "特价"
            }else {
                return ""
            }
        }
        var price = ""
        switch tag {
        case "vip":
            price = XTManageCenter.showPriceInComma(source: (self.detailModel?.data?.memberPrice ?? 0).cleanZero)        case "特价":
            price = XTManageCenter.showPriceInComma(source: (self.detailModel?.data?.discountPrice ?? 0).cleanZero)
        default:
            price = XTManageCenter.showPriceInComma(source: (self.detailModel?.data?.price ?? 0).cleanZero)
        }
        return price
    }
    
    
    
    ///选参数
    func selectTagAction(secName: NSInteger, selectItem: ItemsModel) {
        if selectItem.able ?? false == false {
            return
        }
        
        //返选取消
        for (aIndex, aObj) in self.selectSpec.enumerated() {
            if aObj.id ?? 0 == secName {
                if aObj.parameItem?.id == selectItem.id {
                    self.selectSpec[aIndex].parameItem = nil
                }else{
                    self.selectSpec[aIndex].parameItem = selectItem
                }
            }
        }
        
        self.specList.forEach { aItem in
            aItem.items?.forEach({ its in
                if aItem.id == secName {
                    //相同的组，先取返，后选中
                    if its.id == selectItem.id {
                        its.select = !(selectItem.select ?? false)
                    }else{
                        its.select = false
                    }
                }
                its.able = self.isTagEnAble(secName: aItem.name ?? "", tag: its)
            })
        }
        self.tableView.reloadData()
    }
    
    
    //判断是否可选中
    func isTagEnAble(secName: String, tag: ItemsModel) -> Bool {
        var copySelectSpec: [SelectSpecModel] = []
        copySelectSpec = self.selectSpec
        
        for (pIndex, aObj) in copySelectSpec.enumerated() {
            if aObj.name == secName {
                copySelectSpec[pIndex].parameItem = tag
                break
            }
        }
        var flag = false
        
        for item in self.skuList {
            if (item.availableStock ?? 0) > 0 {
                var num: NSInteger = 0
                for k in copySelectSpec {
                    if k.parameItem != nil {
                        let spec = item.parameterItems ?? []
                        let tempFlag = self.judgeTagContailChild(spec: spec, k: k.parameItem!)
                        if tempFlag {
                            num = num + 1
                        }
                    }else{
                        num = num + 1
                    }
                }
                
                if num == self.specList.count {
                    flag = true
                    break
                }
            }
            
        }
        return flag
    }
    
    ///判断规格中有没有 {id: 48, name: "红色"} 这种参数
    private func judgeTagContailChild(spec: [SpecificationModel], k: ItemsModel) -> Bool{
        var flag = false;
        for aObj in spec {
            if aObj.id == k.id {
                flag = true
                break;
            }
        }
        return flag
    }
    
    ///获取选中的sku
    func getSelectSku() -> SkuDTOListModel? {
        var tempSelectSku: SkuDTOListModel?
        let params = self.selectSpec.compactMap { spec in
            return "\(spec.parameItem?.id ?? 0)"
        }
        let selectId = params.sorted().joined(separator: ",")
        for sku in self.skuList {
            if sku.paramIds == selectId {
                tempSelectSku = sku
                break
            }
        }
        return tempSelectSku
    }
    
    //MARK: -Antion
    
    ///页面展示动画
    @objc func startAnimationAction(){
        
        //计算表的高度
        var tempHH: CGFloat = 0.0
        self.tableView.layoutSubviews()
        
        let cells = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: self.moreSpecificationArray.count))
        if cells != nil {
            tempHH = (cells?.frame.maxY)!
        }
        if (tempHH + TabbarHeight + NavBarHight + 30) > kScreenHeight {
            tempHH = kScreenHeight - TabbarHeight - NavBarHight - 120
        }
        //120是图片高度
        self.tableView.frame.size.height = tempHH
        self.contentView.frame.size.height = tempHH + TabbarHeight + 120
        self.bottomBkgView.frame.origin.y = tempHH + 120
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.3, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor =  UIColor.init(R: 0, G: 0, B: 0, alpha: 0.4)
            self.contentView.frame.origin.y = kScreenHeight - tempHH - TabbarHeight - 120
            self.contentView.round(byRoundingCorners: UIRectCorner.init(arrayLiteral: .topLeft, .topRight), cornerRadi: 10)
        }, completion: { _ in
        })
    }
    
    /// 隐藏,没有点添加到购物车按钮
    @objc func hiddenActionView(){
        let opts = UIViewAnimationOptions.curveEaseInOut
        UIView.animate(withDuration: 0.24, delay: 0, options: opts, animations: {
            self.bkgBtn.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
            self.contentView.frame.origin.y = kScreenHeight
        }, completion: { _ in
            self.dismiss(animated: false) {
                if self.hiddenActionViewBlock != nil {
                    self.hiddenActionViewBlock()
                }
            }
        })
    }
    
    //关闭
    @objc func cancelBtnAction(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.hiddenActionView()
        }
    }
    
    //确定
    @objc func addShoppingCarBtnAntion() {
        
        if let sku = self.getSelectSku() {
            self.requestcartAddNum(skuId: sku.id ?? 0, quantity: self.quantity)
        }else{
            //说明找不到sku 有可能参数没有选中
            for aItem in self.selectSpec {
                if aItem.parameItem == nil {
                    //说明这个参数没有选中
                    self.view.makeToast(message: String(format: "%@%@", MMLocalizedString("please_select", comment: "请选择"), aItem.name ?? ""))
                    break;
                }
            }
        }
    }
    
}

extension ProductPecSheetViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.moreSpecificationArray.count + 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if (self.moreSpecificationArray.count) == indexPath.section {
            let cell = tableView.dequeueReusableCell(withIdentifier: "AddNumTableViewCell", for: indexPath) as! AddNumTableViewCell
            
            cell.numTextField.text = "\(self.quantity)"
            
            if self.quantity == 1 {
                cell.subtractBtn.isUserInteractionEnabled = false
                cell.subtractBtn.setImage(UIImage(named: "icon_subtract_gray"), for: .normal)
            }else{
                cell.subtractBtn.isUserInteractionEnabled = true
                cell.subtractBtn.setImage(UIImage(named: "icon_subtract_car"), for: .normal)
            }
            
            weak var weakSelf = self
            //添加购物车+1
            cell.addShoppingCarNumBlock = {
                let addNum = self.quantity + 1
                self.quantity = addNum
                self.tableView.reloadData()
                self.alterNumPrice()
            }
            
            
            //购物车数量 -1
            cell.subtractShoppingCarNumBlock = {
                var addNum = self.quantity - 1
                if addNum == 0 {
                    addNum = 1
                }
                self.quantity = addNum
                self.tableView.reloadData()
                self.alterNumPrice()
            }
            
            //修改
            cell.modifyShopingCarNumBlock = {(textField: UITextField) in
                if textField.text ?? "" == "0" {//最少1
                    weakSelf?.tableView.reloadData()
                    return
                }
                self.quantity = Int(textField.text ?? "1")!
                self.tableView.reloadData()
                self.alterNumPrice()
            }
            
            return cell
            
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SkuTableViewCell", for: indexPath) as! SkuTableViewCell
            if self.moreSpecificationArray.count > 0 {
                let model = self.moreSpecificationArray[indexPath.section]
                cell.setItemsArray(itemData: model)
            }
            cell.delegate = self
            cell.clipsToBounds = true
        
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 60))
        bgView.backgroundColor = .clear
        
        let titleLab = UILabel(frame: CGRect(x: 18, y: 30, width: kScreenWidth - 36, height: 20))
        titleLab.textColor = Theme.titleLabColor
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 15)
        bgView.addSubview(titleLab)
        if self.moreSpecificationArray.count > section {
            let model = self.moreSpecificationArray[section]
            titleLab.text =  model.name ?? ""
        }
        
        return bgView
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        bgView.backgroundColor = .clear
        return bgView
    }
}


///选参数代理
extension ProductPecSheetViewController: SkuTableViewCellDelegate {
    func didSelectParameter(secData: ParametersModel, param: ItemsModel) {
        self.selectTagAction(secName: secData.id ?? 0, selectItem: param)
        guard let sku = self.getSelectSku() else {
            return
        }
        self.selectSku = sku
        self.alterNumPrice()
        self.tableView.reloadData()
    }
    
}
